package com.city.project.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class OnlineNumAddAndReduceListener
 *
 */
@WebListener
public class OnlineNumAddAndReduceListener implements HttpSessionAttributeListener {

    /**
     * Default constructor.
     */
    public OnlineNumAddAndReduceListener() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub
        String name = arg0.getName();
        Object value = arg0.getValue();
        System.out.println("session属性增加:名=" + name + ";值=" + value);
        if (name.equals("username")) {
            ServletContext application = arg0.getSession().getServletContext();
            int n = (Integer)application.getAttribute("onlinenum") + 1;
            application.setAttribute("onlinenum", n);
        }
    }

    /**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub
        String name = arg0.getName();
        Object value = arg0.getValue();
        System.out.println("session属性删除:名=" + name + ";值=" + value);
        if (name.equals("username")) {
            ServletContext application = arg0.getSession().getServletContext();
            int n = (Integer)application.getAttribute("onlinenum") - 1;
            application.setAttribute("onlinenum", n);
        }
    }

    /**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub
    }

}
